package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.ProductBean;
import com.project.dao.IProductDao;
import com.project.service.IProductService;
import com.project.util.InfoResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lyl
 * description:
 */
@Service
@Transactional
public class ProductServiceImpl implements IProductService {
    @Autowired
    private IProductDao iProductDao;

    @Override
    public Page<ProductBean> showProductByPage(int pageNum, String productName, String productType, int startNum, int endNum) {
        QueryWrapper<ProductBean> wa = new QueryWrapper<>();
        wa.eq("productType", productType);
        if (startNum != -1) {
            wa.ge("productNum", startNum);
        }
        if (endNum > startNum) {
            wa.le("productNum", endNum);
        }
        if (!"1".equals(productName)) {
            wa.like("productName", productName);
        }
        return iProductDao.selectPage(new Page<>(pageNum, 3), wa);
    }

    @Override
    public ProductBean findProductById(int productId) {
        return iProductDao.selectById(productId);
    }

    @Override
    public InfoResult updateProductPrice(int productId, int salePrice) {
        ProductBean productBean = iProductDao.selectById(productId);
        productBean.setSalePrice(salePrice);
        int x = iProductDao.updateById(productBean);
        if (x == 1) {
            return new InfoResult(0, "产品" + productBean.getProductName() + "更新价格成功");
        }
        return new InfoResult(1, "产品" + productBean.getProductName() + "更新价格失败");
    }

    @Override
    public long addNewProduct(ProductBean productBean) {
        iProductDao.insert(productBean);
        QueryWrapper<ProductBean> wa = new QueryWrapper<>();
        wa.eq("productName", productBean.getProductName());
        return iProductDao.selectOne(wa).getProductId();
    }

    @Override
    public InfoResult updateProductNum(long productId, long purchaseNum, boolean flag) {
        ProductBean p = iProductDao.selectById(productId);
        long total;
        if (flag == true) {
            total = p.getProductNum() + purchaseNum;
        } else {
            total = p.getProductNum() - purchaseNum;

        }
        p.setProductNum((int) total);
        int x = iProductDao.updateById(p);
        if (x == 1) {
            return new InfoResult(0, "更新商品数据成功,当前库存" + total + "件");
        }
        return new InfoResult(1, "库存信息更新失败");
    }


}
